/* eslint-disable no-debugger */ /* eslint-disable no-debugger */
<template>
  <div style="min-height: 800px" class="grade">
    <div class="header">
      <label>
        考试科目：
        <el-select v-model="testSubject" placeholder="请选择" size="mini">
          <el-option label="全部" value=""></el-option>
          <el-option label="低压配电装置" value="0"></el-option>
          <el-option label="带电调换电实训装置" value="1"></el-option>
        </el-select>
      </label>
      <label for="name">
        考试名称：
        <input
          id="name"
          v-model="testName"
          type="btn"
          size="mini"
          placeholder="考试名称"
        />
      </label>
      <label>
        分数类型：
        <el-select v-model="examQtype" size="mini" placeholder="请选择考试类型">
          <el-option label="全部" value=""></el-option>
          <el-option label="培训分数" value="0"></el-option>
          <el-option label="考试分数" value="1"></el-option> </el-select
      ></label>
      <label>
        发布状态：
        <el-select
          v-model="postStatus"
          size="mini"
          placeholder="请选择发布状态"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="未发布" value="0"></el-option>
          <el-option label="已发布" value="1"></el-option> </el-select
      ></label>
      <label>
        考试时间：
        <el-date-picker
          v-model="dateTimes"
          size="mini"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </label>
      <!-- <label for="equipment">
        设备类型:
        <el-select
          v-model="equipment"
          placeholder="请选择活动区域"
        >
          <el-option
            label="高低压设备"
            value="0"
          ></el-option>
          <el-option
            label="高低压设备2"
            value="1"
          ></el-option> </el-select></label> -->
      <el-button type="primary" @click="queTest()"> 查询 </el-button>
      <el-button @click="reset"> 重置 </el-button>
    </div>

    <div class="sdata1">
      <el-table
        ref="testtable"
        :data="examData"
        :row-style="{ height: 0 + 'px', 'text-align': 'center' }"
        :cell-style="{ padding: 3 + 'px', 'text-align': 'center' }"
        height="316"
        style="width: 100%"
        :header-cell-style="tableHeaderColor"
        :row-class-name="tableRowClassName"
        @row-click="clickTr"
      >
        <el-table-column
          prop="equipmentType"
          label="考试科目"
          width="120"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{
              scope.row.equipmentType == 1
                ? "带电调换电实训装置"
                : "低压配电综合装置"
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="examinationName"
          label="考试名称"
          width="90"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column prop="examStatus" label="考试状态">
          <template slot-scope="scope">
            {{
              scope.row.examStatus == 0
                ? "未开始"
                : scope.row.examStatus == 1
                ? "进行中"
                : "完成"
            }}
          </template>
        </el-table-column>
        <el-table-column prop="postStatus" label="发布状态">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.postStatus == 0 ? '' : '#bbb' }">
              {{ scope.row.postStatus == 0 ? "未发布" : "已发布" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="教室"> </el-table-column>
        <el-table-column
          prop="endTime"
          sortable
          label="考试时间"
          width="180"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.startTime }}--{{
              scope.row.endTime
                .replace(" ", ":")
                .replace(/\:/g, "-")
                .split("-")[3]
            }}:{{
              scope.row.endTime
                .replace(" ", ":")
                .replace(/\:/g, "-")
                .split("-")[4]
            }}
          </template>
        </el-table-column>
        <el-table-column prop="time" label="考试已用时" width="100">
          <template slot-scope="scope">
            {{
              scope.row.examStatus == 0
                ? "未开始"
                : scope.row.examStatus == 1
                ? parseInt(
                    (new Date() - new Date(scope.row.startTime)) / (1000 * 60)
                  ) + "分钟"
                : (new Date(scope.row.endTime) -
                    new Date(scope.row.startTime)) /
                    (1000 * 60) +
                  "分钟"
            }}
          </template>
        </el-table-column>
        <el-table-column prop="shouldAttend" label="应到人数">
        </el-table-column>
        <el-table-column prop="actualNumber" label="已到人数">
        </el-table-column>
        <el-table-column prop="examsNumber" label="已考人数"> </el-table-column>

        <el-table-column fixed="right" label="操作" width="160" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              @click="
                fractionClick(
                  scope.row,
                  scope.row.examinationId,
                  scope.row.examinationName
                )
              "
            >
              <i class="el-icon-zoom-in"></i> 查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              :disabled="scope.row.postStatus == 1"
              @click="updatePost(scope.row.examinationId)"
            >
              <i class="el-icon-check"></i> 发布
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page="currentPage"
        :page-sizes="[8, 15, 30, 50]"
        :page-size="8"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>

      <div v-show="isFraction" style="min-height: 450px; max-height: 500px">
        <div class="header kscx">
          <label for="name"> 姓名: </label>
          <input
            id="name"
            v-model="studentName"
            type="btn"
            placeholder="用户名"
          />
          <el-button type="primary" @click="query()"> 查询 </el-button>
          <el-button type="primary" @click="exportExcel"> 导出表格 </el-button>
        </div>
        <el-table
          id="out-table"
          ref="table"
          :data="gradeTableData"
          height="316"
          :row-style="{ height: 0 + 'px' }"
          :header-cell-style="tableHeaderColor"
          :cell-style="columnStyle"
        >
          <el-table-column prop="studentName" label="姓名" sortable width="90">
          </el-table-column>

          <el-table-column
            prop="examinationName"
            label="考试名称"
            min-width="120"
          >
          </el-table-column>
          <el-table-column
            prop="equipmentType"
            label="设备类型"
            min-width="150"
          >
            <template slot-scope="scope">
              {{
                scope.row.equipmentType == 1
                  ? "低压配电综合装置"
                  : "带电调换电实训装置"
              }}
            </template>
          </el-table-column>
          <el-table-column prop="equipmentName" label="考位" width="130">
          </el-table-column>
          <!-- <el-table-column
            prop="endTime"
            label="考试时间"
            width="210"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.startTime != null">
                {{ scope.row.startTime }}--{{
                  scope.row.endTime
                    .replace(" ", ":")
                    .replace(/\:/g, "-")
                    .split("-")[3]
                }}:{{
                  scope.row.endTime
                    .replace(" ", ":")
                    .replace(/\:/g, "-")
                    .split("-")[4]
                }}</span>
              <span v-else>未统计</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="helmetDetection" label="安全帽" min-width="65">
            <span
              slot-scope="scope"
              :style="{ color: scope.row.helmetDetection == 0 ? '' : 'red' }"
            >
              {{ scope.row.helmetDetection }}
            </span>
          </el-table-column>
          <el-table-column prop="toolingDetection" label="工装" min-width="55">
            <span
              slot-scope="scope"
              :style="{ color: scope.row.toolingDetection == 0 ? '' : 'red' }"
            >
              {{ scope.row.toolingDetection }}
            </span>
          </el-table-column>
          <el-table-column prop="outDetection" label="越界" min-width="55">
            <span
              slot-scope="scope"
              :style="{ color: scope.row.outDetection == 0 ? '' : 'red' }"
            >
              {{ scope.row.outDetection }}
            </span>
          </el-table-column>
          <el-table-column
            prop="peopleDetection"
            label="人员聚集"
            min-width="80"
          >
            <span
              slot-scope="scope"
              :style="{ color: scope.row.peopleDetection == 0 ? '' : 'red' }"
            >
              {{ scope.row.peopleDetection }}
            </span>
          </el-table-column>
          <el-table-column
            prop="articleDetection"
            label="物品遗漏"
            min-width="80"
          >
            <span
              slot-scope="scope"
              :style="{ color: scope.row.articleDetection == 0 ? '' : 'red' }"
            >
              {{ scope.row.articleDetection }}
            </span>
          </el-table-column>

          <el-table-column prop="timeOutDetection" label="超时" min-width="55">
            <span
              slot-scope="scope"
              :style="{ color: scope.row.timeOutDetection == 0 ? '' : 'red' }"
            >
              {{ scope.row.timeOutDetection }}
            </span>
          </el-table-column>
          <el-table-column prop="timeOutDetection" label="迟到" min-width="55">
            <span
              slot-scope="scope"
              :style="{ color: scope.row.timeOutDetection == 0 ? '' : 'red' }"
            >
              {{ scope.row.timeOutDetection }}
            </span>
          </el-table-column>
          <el-table-column prop="examScore" label="分数" min-width="55">
            <template slot-scope="scope">
              {{ scope.row.examScore ? scope.row.examScore : 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="postStatus" label="发布状态">
            <span
              slot-scope="scope"
              :style="{ color: scope.row.postStatus == 1 ? '' : 'red' }"
            >
              {{ scope.row.postStatus == 0 ? "未发布" : "已发布" }}
            </span>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="165">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                :disabled="scope.row.postStatus == 1"
                @click="
                  changeGrade(
                    scope.row.examinationId,
                    scope.row.examScore,
                    scope.row.studentId
                  )
                "
              >
                <i class="el-icon-edit"></i> 修正
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="
                  compileClick(1, scope.row.examinationId, scope.row.studentId)
                "
              >
                <i class="el-icon-zoom-in"></i> 查看图片
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="fractiontotal > 10"
          background
          :current-page="fractionPage"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="fractiontotal"
          @size-change="fractionChange"
          @current-change="fractionCurrentChange"
        >
        </el-pagination>
      </div>

      <!-- 分数修改弹窗 -->
      <el-dialog v-dialogDrag title="分数修改" :visible.sync="GradeVisible">
        <el-form id="garform" ref="graform" :model="graform" :rules="garRules">
          <el-form-item
            label="请输入正确的分数："
            :label-width="formLabelWidth"
            prop="grade"
          >
            <el-input v-model="graform.grade" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="GradeVisible = false"> 取 消 </el-button>
          <el-button type="primary" @click="gradeSubmit('graform')">
            确 定
          </el-button>
        </div>
      </el-dialog>

      <!-- 图片展示 -->
      <el-dialog
        v-dialogDrag
        title="抓拍图片(点击图片查看大图)"
        :visible.sync="centerDialogVisible"
        width="80%"
        top="10vh"
        center
      >
        <dd
          v-for="ite in imgtype"
          :key="ite.id"
          :class="{ styleName: ite.id == imgTypeId }"
          @click="compileClick(ite.id, examid, stuid)"
        >
          {{ ite.title + "图片" }}
        </dd>

        <ul class="imglist">
          <li
            v-for="(item, index) in imgdata"
            v-show="imgdata.length > 0"
            :key="index"
            @click="popover($event)"
          >
            <el-image
              style="width: 100%; max-height: 10vh"
              :src="item"
              fit="contain"
              :preview-src-list="imgdata"
              @error="imgExists($event)"
            >
            </el-image>
          </li>

          <h1 v-show="imgdata.length <= 0">未找到违规图片!</h1>
        </ul>
        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="centerDialogVisible = false"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
import {
  queryFraction,
  queryImage,
  queryTestInfo,
  gradeChange,
  updatePostStatus,
} from "@/api";
export default {
  name: "Grade",
  data() {
    return {
      centerDialogVisible: false,
      tableHeight: 300,
      ll: -1,
      isFraction: false,
      imgdata: [],
      imgtype: [
        { id: 1, title: "越界" },
        { id: 2, title: "人员聚集" },
        { id: 3, title: "安全帽" },
        { id: 4, title: "抓拍" },
      ],
      imgTypeId: 1,
      examid: "", // 考试id 用于查询图片
      stuid: "", // 学生id 用于查询图片
      graform: { grade: "", ksid: "", xsid: "" },
      garRules: {
        grade: [
          {
            required: true,
            pattern: /^([1-9]?\d|100)$/,
            message: "请输入正确的分数!",
            trigger: "change",
          },
        ],
      },
      formLabelWidth: "150px",
      gradeTableData: [],
      examData: [],
      tName: "", // 点击查看的考试名称
      GradeVisible: false, // 成绩修改弹窗
      studentName: "", // 查询学生姓名
      testName: "", // 考试名称
      testSubject: "", //考试科目
      postStatus: "", //发布状态
      date: [],
      invigilateName: "",
      equipment: "",
      total: 10,
      dateTimes: [], // 0 开始时间 1 结束时间
      elImgUrl: "", // 大图img
      currentPage: 1,
      limit: 8,
      examinationId: "",
      fractionPage: 1, // 学生信息页码
      fractiontotal: 10, //学生信息总条数
      fractionlimit: 10, //学生信息条数
      EQType: "",
      examQtype: "", //查询考试类型
      examType: 1, // 查询考试&培训信息
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
        disabledDate(v) {
          return v.getTime() > Date.now();
        },
      },
      // 定义查询考试信息
      queTest: (
        examinationName = this.testName,
        equipmentType = this.testSubject,
        postStatus = this.postStatus,
        startTime = this.dateTimes[0],
        endTime = this.dateTimes[1],
        usersId = localStorage.getItem("usersId"),
        page = this.currentPage,
        limit = this.limit,
        examType = this.examQtype
      ) => {
        queryTestInfo({
          equipmentType,
          examinationName,
          postStatus,
          startTime,
          endTime,
          usersId,
          page,
          limit,
          examType,
        })
          .then((res) => {
            this.examData = res.data;
            this.total = res.count;
          })
          .catch((err) => {
            console.log(err);
          });
      },
      // 根据考试查询学生信息
      query(
        page = this.fractionPage,
        limit = this.fractionlimit,
        studentName = this.studentName,
        usersId = localStorage.getItem("usersId"),
        examinationId = this.examinationId,
        examType = this.examType
      ) {
        queryFraction({
          page,
          limit,
          usersId,
          studentName,
          examinationId,
          examType,
        })
          .then((res) => {
            this.isFraction = true;
            this.gradeTableData = res.data;
            this.fractiontotal = res.count;
          })
          .catch((err) => {
            console.log(err);
          });
      },
      // 分数修改
      gradexg(
        examScore = this.graform.grade,
        examinationId = this.graform.ksid,
        studentId = this.graform.xsid
      ) {
        gradeChange({ examScore, examinationId, studentId }).then((res) => {
          if (res.result_code == 200) {
            this.$message({
              message: "分数修改成功",
              type: "success",
            });
            this.query();
          }
        });
      },
      // 发布成绩
      updatePost(exa) {
        this.$confirm("发布后将无法修改成绩, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            updatePostStatus({ examinationId: exa }).then((res) => {
              console.log(res);
              if (res.result_code == 200) {
                this.$message({
                  message: "发布成功",
                  type: "success",
                });
                this.queTest();
              } else {
                this.$message.error("发布失败!请稍后重试");
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消发布",
            });
          });
      },
    };
  },
  mounted() {
    this.queTest();
    this.examinationId = this.$route.params.id;
    if (this.examinationId) {
      this.query();
    }
  },
  activated() {
    console.log("组件激活");
  },
  methods: {
    //定义导出Excel表格事件
    exportExcel() {
      let fix = document.querySelector("#out-table .el-table__fixed-right");
      let fixh = document.querySelector(
        "#out-table .el-table__header-wrapper th.is-hidden"
      );
      if (fixh) {
        fixh.remove();
      }
      let ll = document.querySelectorAll(
        "#out-table .el-table__body-wrapper tr td.is-hidden"
      );
      if (ll) {
        ll.forEach((item) => {
          item.remove();
        });
      }

      let wb;
      var xlsxParam = { raw: true };
      if (fix) {
        document.querySelector("#out-table").removeChild(fix);

        let elt = document.getElementById("out-table");
        wb = XLSX.utils.table_to_book(elt, xlsxParam);
        document.querySelector("#out-table").appendChild(fix);
      } else {
        wb = XLSX.utils.table_to_book(
          document.querySelector("#out-table"),
          xlsxParam
        );
      }
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          this.tName + "系统评分.xlsx"
        );
        // setTimeout(() => {
        //   elt.appendChild(fix);
        // }, 5000);
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }

      // elt.appendChild(fix);
      return wbout;
    },

    fractionClick(row, examinationId, examinationName) {
      this.examinationId = examinationId;
      this.tName = examinationName;
      this.ll = this.examData.indexOf(
        this.examData.filter((d) => d.examinationId == this.examinationId)[0]
      );
      this.query();
    },
    clickTr(ee) {
      console.log(ee);
      this.examinationId = ee.examinationId;
      this.tName = ee.examinationName;
      this.examType = ee.examType;
      this.ll = this.examData.indexOf(
        this.examData.filter((d) => d.examinationId == this.examinationId)[0]
      );
      this.query();
    },

    compileClick(imageType = 1, examinationId, studentId) {
      this.examid = examinationId;
      this.stuid = studentId;
      this.imgTypeId = imageType;
      queryImage({ examinationId, studentId, imageType })
        .then((res) => {
          if (res.result_code == 200) {
            console.log(res);
            this.imgdata = [];
            res.data.forEach((item) => {
              this.imgdata.push("platform/management/detection/" + item);
            });
            console.log(this.imgdata);
            this.centerDialogVisible = true;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 修改分数
    changeGrade(examinationId, examScore, studentId) {
      this.graform.ksid = examinationId;
      this.graform.grade = examScore;
      this.graform.xsid = studentId;
      this.GradeVisible = true;
    },
    // 提交分数
    gradeSubmit(aa) {
      this.$refs[aa].validate((valid) => {
        if (valid) {
          this.gradexg();
          this.GradeVisible = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 重置表单
    reset: function () {
      this.testName = "";
      this.postStatus = "";
      this.testSubject = "";
      this.dateTimes = [];
    },

    tableHeaderColor({ rowIndex }) {
      if (rowIndex === 0) {
        return "background-color: #009A9A;color: #fff;font-weight: 500;'font-size':'14px';height:20px;padding:8px 0;text-align:center";
      }
    },

    // 分页功能

    handleSizeChange(val) {
      this.limit = val;
      this.queTest();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.queTest();
    },
    fractionChange(val) {
      this.fractionlimit = val;
      this.query();
    },
    fractionCurrentChange(val) {
      this.fractionPage = val;
      this.query();
    },
    popover(e) {
      this.elImgUrl = e.target.currentSrc;
    },

    columnStyle({ columnIndex }) {
      if (
        columnIndex == 5 ||
        columnIndex == 6 ||
        columnIndex == 7 ||
        columnIndex == 8 ||
        columnIndex == 9 ||
        columnIndex == 4
      ) {
        return "background:#FEF2E2;padding:3px";
      } else {
        return "padding:3px";
      }
    },

    tableRowClassName({ rowIndex }) {
      //  console.log(row,rowIndex);
      if (rowIndex == this.ll) {
        return "warning-row";
      }
      return "";
    },
    // 图片加载失败
    imgExists(e) {
      //默认图片
      var imgUrl = require("../../assets/jzsb.png");
      var img = e.srcElement;
      img.src = imgUrl;
      //判断图片大小是否大于0 或者 图片高度与宽度都大于0
      if (img.filesize > 0 || (img.width > 0 && img.height > 0)) {
        e.src = imgUrl;
      } else {
        //默认图片也不存在的时候
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.header {
  padding: 5px 10px;
  background: rgba(0, 128, 128, 1);
  color: white;
  font-size: 14px;
  text-align: left;
  border-bottom: 1px solid #016c6c;
  label {
    display: inline-block;
    text-align: left;
    margin-right: 15px;
  }
  input {
    padding: 0 10px;
    color: #666;
    line-height: 25px;
    border-radius: 5px;
    margin: 5px 10px 5px 0;
    width: 80px;
  }
  .el-table__body tr.current-row > td {
    background-color: #010102 !important;
    color: #fff;
  }
  .el-table {
    border-top: 1px solid #12a3a3;
  }
  .el-button {
    margin-left: 10px;
  }
  .el-select {
    width: 90px;
    line-height: 5px;
    height: 5px;
  }

  .el-date-editor {
    padding: 0 0 0 10px;
    align-items: baseline;
    margin-right: 5px;
    width: 185px;
  }

  .el-input__icon {
    line-height: 25px;
  }
}
#garform .el-input {
  width: 200px;
  float: left;
}

.imglist {
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;

  --wid: 13.42%;
  li {
    box-sizing: border-box;
    width: var(--wid);
    min-width: var(--wid);
    max-width: var(--wid);
    margin-right: 1%;
    margin-bottom: 20px;
    &:nth-child(7n) {
      margin-right: 0;
    }
  }
}

.el-dialog__body {
  dd {
    float: left;
    cursor: pointer;
    padding: 10px 15px;
    border-radius: 5px;
    margin: 0 15px 15px 0;
    color: white;
    background: #006065;
  }
  .styleName {
    background: #1db3b3;
  }
}
.el-dialog__body h1 {
  text-align: center;
  padding: 35px;
  font-size: 28px;
  color: #f1b549;
}
</style>
